//
//  SINALoginViewController.m
//  sinashebao
//
//  Created by  androidlongs on 2017/11/30.
//  Copyright © 2017年  androidlongs. All rights reserved.
//  老师测试帐号 13156789098

#import "SINALoginViewController.h"
#import "SINAStudentMainViewController.h"
#import "SINATeacherMainViewController.h"
#import "SINANavLoginViewController.h"
#import "SINAStudentTabBarViewController.h"
#import "SINATeacherTabBarViewController.h"
#import "SINARegisterViewController.h"
#import "SINAlertPasswordViewController.h"
#import "SINAIdentitySelectViewController.h"
#import "SINAUserModel.h"
#import "SINAHttpRequestUtils.h"
#import "SINAUiviewClickLiserner.h"
#import "PTQQSdkCall.h"
#import "PTWeChatSdkCall.h"
#import "WXApiManager.h"

@interface SINALoginViewController ()<UITextFieldDelegate,TencentSessionDelegate,TencentLoginDelegate,WXApiManagerDelegate>

{
    time_t loginTime;
}

@property (weak, nonatomic) IBOutlet UITextField *userNameTextField;
@property (weak, nonatomic) IBOutlet UIButton *loginButton;
@property (weak, nonatomic) IBOutlet UITextField *userPasswordTextField;



@property (weak, nonatomic) IBOutlet UIImageView *pageBackgroundImageView;
@property (weak, nonatomic) IBOutlet UIImageView *appIconImageView;
@property (weak, nonatomic) IBOutlet UILabel *appNameLabel;

@property (weak, nonatomic) IBOutlet UIView *usernameDiviView;
@property (weak, nonatomic) IBOutlet UIView *passworDiviView;


@property (weak, nonatomic) IBOutlet UIButton *alertPasswordButton;
@property (weak, nonatomic) IBOutlet UIButton *registerButton;


@property (weak, nonatomic) IBOutlet UIView *qqLoginView;
@property (weak, nonatomic) IBOutlet UIImageView *qqLoginIconImageView;

@property (weak, nonatomic) IBOutlet UIView *weixinLoginView;
@property (weak, nonatomic) IBOutlet UIImageView *weixinLoginIconImageView;


@property (weak, nonatomic) IBOutlet UILabel *otherLoginFlagLabel;
@property (weak, nonatomic) IBOutlet UIView *diviLeftView;
@property (weak, nonatomic) IBOutlet UIView *diviRightView;

//@property(assign,nonatomic) BOOL isClick;

@end

@implementation SINALoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title =@"登录";
    [self.view setBackgroundColor:[UIColor whiteColor]];
    //667
    //480
    DLog(@"mainh is %ld",(long)mainH);
//    self.isClick = NO;
    
    
    self.pageBackgroundImageView.frame = CGRectMake(0, 0, mainW,mainH);
    if (mainH>600) {
        if (IS_IPHONE_X) {
            self.appIconImageView.frame = CGRectMake(30, 85+20, 32,38);
            self.appNameLabel.frame=CGRectMake(85, 94+20, 82, 21);
        } else {
            self.appIconImageView.frame = CGRectMake(30, 85, 32,38);
            self.appNameLabel.frame=CGRectMake(85, 94, 82, 21);
        }
        
        self.userNameTextField.frame=CGRectMake(26, CGRectGetMaxY(self.appIconImageView.frame)+60, mainW-26*2, 31);
        self.usernameDiviView.frame=CGRectMake(26, CGRectGetMaxY(self.userNameTextField.frame), CGRectGetWidth(self.usernameDiviView.frame), 1);
        
        self.userPasswordTextField.frame=CGRectMake(26, CGRectGetMaxY(self.usernameDiviView.frame)+16, mainW-26*2, 31);
        self.passworDiviView.frame=CGRectMake(26, CGRectGetMaxY(self.userPasswordTextField.frame), CGRectGetWidth(self.usernameDiviView.frame), 1);
        
        self.loginButton.frame=CGRectMake(26, CGRectGetMaxY(self.passworDiviView.frame)+60, mainW-26*2, 38);
        
        self.alertPasswordButton.frame=CGRectMake(26, CGRectGetMaxY(self.loginButton.frame)+20,81, 30);
        
        self.registerButton.frame=CGRectMake(mainW-26-67, CGRectGetMaxY(self.loginButton.frame)+20,67, 30);
        
    } else {
        self.appIconImageView.frame = CGRectMake(30, 40, 32,38);
        self.appNameLabel.frame=CGRectMake(85, 50, 82, 21);
        
        self.userNameTextField.frame=CGRectMake(26, CGRectGetMaxY(self.appIconImageView.frame)+40, mainW-26*2, 31);
        self.usernameDiviView.frame=CGRectMake(26, CGRectGetMaxY(self.userNameTextField.frame), CGRectGetWidth(self.userNameTextField.frame), 1);
        
        self.userPasswordTextField.frame=CGRectMake(26, CGRectGetMaxY(self.usernameDiviView.frame)+16, mainW-26*2, 31);
        self.passworDiviView.frame=CGRectMake(26, CGRectGetMaxY(self.userPasswordTextField.frame), CGRectGetWidth(self.usernameDiviView.frame), 1);
        
        self.loginButton.frame=CGRectMake(26, CGRectGetMaxY(self.passworDiviView.frame)+60, mainW-26*2, 38);
        
        self.alertPasswordButton.frame=CGRectMake(26, CGRectGetMaxY(self.loginButton.frame)+20,81, 30);
        
        self.registerButton.frame=CGRectMake(mainW-26-67, CGRectGetMaxY(self.loginButton.frame)+20,67, 30);
        
    }
    
    
    [self.registerButton setTitleColor:baseButtonBackGroundColor forState:UIControlStateNormal];
    [self.alertPasswordButton setTitleColor:baseButtonBackGroundColor forState:UIControlStateNormal];
    
    
    
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    dict[NSForegroundColorAttributeName] = [UIColor colorWithHexString:@"#DDDDDD"];
    NSAttributedString *attribute = [[NSAttributedString alloc] initWithString:@"请输入手机号" attributes:dict];
    [self.userNameTextField setAttributedPlaceholder:attribute];
    
    
    
    NSMutableDictionary *dict2 = [NSMutableDictionary dictionary];
    dict2[NSForegroundColorAttributeName] = [UIColor colorWithHexString:@"#DDDDDD"];
    NSAttributedString *attribute2 = [[NSAttributedString alloc] initWithString:@"请输入密码" attributes:dict2];
    [self.userPasswordTextField setAttributedPlaceholder:attribute2];
    
    //设置lable的圆角显示
    self.loginButton.layer.cornerRadius =5;
    //设置lable的边框 宽度为1
    self.loginButton.layer.borderWidth=0;
    //设置lable的边框颜色
    self.loginButton.layer.borderColor=[UIColor redColor].CGColor;
    //设置 显示大小范围为 border内容范围中
    self.loginButton.clipsToBounds = YES;
    [self.loginButton setBackgroundColor: baseButtonBackGroundColor];
    
    //[self.userNameTextField setPlaceholder:@"请输入用户名"];
    //[self.userPasswordTextField setPlaceholder:@"请输入密码"];
    self.navigationController.navigationBar.barTintColor = [UIColor whiteColor];
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    //    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"back"] style:UIBarButtonItemStylePlain target:self action:@selector(backAction)];
    
    //self.navigationItem.leftBarButtonItems = @[leftItem];
    
    UIImage *image=[UIImage imageNamed:@"back"];
    UIBarButtonItem* backButton=[[UIBarButtonItem alloc] initWithImage:image landscapeImagePhone:image style:UIBarButtonItemStylePlain target:self action:@selector(backAction)];
    
    
    if (self.isShowBack) {
        self.navigationItem.leftBarButtonItem= backButton;
    } else {
        self.navigationItem.leftBarButtonItem= nil;
    }
    
    self.userNameTextField.delegate=self;
    self.userPasswordTextField.delegate=self;
    self.userNameTextField.returnKeyType = UIReturnKeyDone;
    self.userPasswordTextField.returnKeyType = UIReturnKeyDone;
    //使你输入的密码变为小原点，及一般应用都这么做
    self.userPasswordTextField.secureTextEntry = YES;
    WeakSelf;
    [[SINAUiviewClickLiserner alloc]viewClickFunction:self.view andWithBlick:^(UIView *view) {
        [weakSelf.view endEditing:YES];
    }];
    
    self.qqLoginView.frame=CGRectMake(0, mainH-120, mainW/2, 40);
    self.qqLoginView.backgroundColor=[UIColor clearColor];
    self.weixinLoginView.frame=CGRectMake(mainW/2, mainH-120, mainW/2, 40);
    self.weixinLoginView.backgroundColor=[UIColor clearColor];
  self.qqLoginIconImageView.frame=CGRectMake(CGRectGetWidth(self.qqLoginView.frame)-23-40, 12, 23, 24);
    self.weixinLoginIconImageView.frame=CGRectMake(40, 12, 31, 26);
    
    self.otherLoginFlagLabel.frame=CGRectMake(0, mainH-150, mainW, 21);
    
    self.diviLeftView.frame=CGRectMake(40, mainH-150+11, mainW/2-40-48, 1);
    self.diviRightView.frame=CGRectMake(mainW/2+40, mainH-150+11, mainW/2-40-48, 1);
    
    [[SINAUiviewClickLiserner alloc]viewClickFunction:self.qqLoginView andWithBlick:^(UIView *view) {

        time_t currentTime;
        time(&currentTime);
        if ((currentTime - loginTime)>3) {
            
//            NSLog(@"%@",@"进来了");
            [weakSelf qqLoginFunction];
            loginTime = currentTime;
        }
    }];
    [[SINAUiviewClickLiserner alloc]viewClickFunction:self.weixinLoginView andWithBlick:^(UIView *view) {
//        if (!weakSelf.isClick) {
//            weakSelf.isClick=YES;
             [weakSelf weixinLoginFunction];
//        }
    }];
    
    [WXApiManager sharedManager].delegate = self;
    
    loginTime = 0;
    
    self.weixinLoginView.hidden=YES;
    
    if (mainH<=600) {
        self.qqLoginView.frame=CGRectMake(0, mainH-70, mainW, 40);
        self.qqLoginIconImageView.frame=CGRectMake(CGRectGetWidth(self.qqLoginView.frame)/2-23/2, 12, 23, 24);
        
        self.otherLoginFlagLabel.frame=CGRectMake(0, mainH-100, mainW, 21);
        
        self.diviLeftView.frame=CGRectMake(40, mainH-100+11, mainW/2-40-48, 1);
        self.diviRightView.frame=CGRectMake(mainW/2+40, mainH-100+11, mainW/2-40-48, 1);
        
    } else {
        self.qqLoginView.frame=CGRectMake(0, mainH-120, mainW, 40);
        self.qqLoginIconImageView.frame=CGRectMake(CGRectGetWidth(self.qqLoginView.frame)/2-23/2, 12, 23, 24);
        
    }
    
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if (textField == self.userNameTextField) {
        if ([textField.text length] > 10) {
            textField.text = [textField.text substringWithRange:NSMakeRange(0, 10)];
            [textField.undoManager removeAllActions];
            [textField becomeFirstResponder];
        }
    }
    return YES;
    
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    if (textField == self.userNameTextField) {
        //self.usernameTextfield放弃第一响应者，而self.passwordTextfield变为第一响应者
        [self.userNameTextField resignFirstResponder];
        [self.userPasswordTextField becomeFirstResponder];
    } else if(textField == self.userPasswordTextField) {
        //self.passwordTextfield放弃第一响应者，并调用登录函数
        [self.userPasswordTextField resignFirstResponder];
        [self.loginButton sendActionsForControlEvents:UIControlEventTouchUpInside];
        //[self clickLoginBtn:self.loginBtn];
    }
    return YES;
}
//跳转修改密码页面
- (IBAction)alertPasswordClick:(UIButton *)sender {
    //    SINAlertPasswordViewController *alertPasswordController = [[SINAlertPasswordViewController alloc]initWithNibName:@"SINAlertPasswordViewController" bundle:nil];
    //    [self.navigationController pushViewController:alertPasswordController animated:YES];
    SINARegisterViewController *registerController =[[SINARegisterViewController alloc]initWithNibName:@"SINARegisterViewController" bundle:nil];
    registerController.pageType=1;
    [self.navigationController pushViewController:registerController animated:YES];
}
//跳转注册页面
- (IBAction)registerClickFunction:(UIButton *)sender {
    SINARegisterViewController *registerController =[[SINARegisterViewController alloc]initWithNibName:@"SINARegisterViewController" bundle:nil];
    registerController.pageType=0;
    [self.navigationController pushViewController:registerController animated:YES];
}
//登录
- (IBAction)loginClickFunction:(UIButton *)sender {
    
    [self.view endEditing:YES];
    NSString *userName = self.userNameTextField.text;
    NSString *userPassword = self.userPasswordTextField.text;
    
    if (userName==nil||[userName isEqualToString:@""]) {
        WISAlertView *alertView =   [[WISAlertView alloc]initWithTitle:@"提示" message:@"请输入手机号" sureBtn:@"确定"
                                                             cancleBtn:nil];
        [alertView showXLAlertView];
        return;
    }
    if (userPassword==nil||[userPassword isEqualToString:@""]) {
        WISAlertView *alertView =   [[WISAlertView alloc]initWithTitle:@"提示" message:@"请输入密码" sureBtn:@"确定"
                                                             cancleBtn:nil];
        [alertView showXLAlertView];
        return;
    }
    
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults setValue:userName forKey:@"userPhone"];
    [userDefaults synchronize];
    
    //登录请求参数
    NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
    //1.学生phone
    [dict setObject:userName forKey:@"phone"];
    //    NSString *passwordSign = [SINAMd5Utils md5:userPassword];
    //2.未加密密码
    [dict setObject:userPassword forKey:@"passwords"];
    //获取系统时间戳
    NSDate* date1 = [NSDate date];
    NSTimeInterval time1 =[date1 timeIntervalSince1970];
    NSString *timeString = [NSString stringWithFormat:@"%.0f",time1];
    //3.签名时间 当前时间
    [dict setObject:timeString forKey:@"signtimes"];
    //4.唯一标识符
    NSString *uuid = [NSUUID UUID].UUIDString;
    [dict setObject:uuid forKey:@"signuid"];
    //5.签名
    NSString *signflag = [SINAMd5Utils md5:[NSString stringWithFormat:@"%@%@",uuid,timeString]];
    [dict setObject:signflag forKey:@"signflag"];
    
    
    NSMutableDictionary *dict2 = [[NSMutableDictionary alloc]init];
    
    [dict2 setObject:[SINAHttpRequestUtils encodeDicParams:dict] forKey:@"sj"];
    
    [self startLoading];
    
    WeakSelf;
    [CXAFNHttpRequestUtils httpPostRequest:[NSString stringWithFormat:@"%@%@",baseUrl,userLoginUrl] withParamters:dict2 success:^(id responseData) {
        
        NSString *code = responseData[@"code"];
        
        [weakSelf stopLoading];
        
        if ([code isEqualToString:@"1000"]) {
            NSDictionary *result = responseData[@"content"];
            
            SINAUserModel *userModel=[SINAUserModel userWithDict:result];
            SINACommonUserHelper *userHelper=[SINACommonUserHelper share];
            userModel.userPassword =userPassword;
            [userHelper saveUserModel:userModel];
            
            
            if (userModel.userUid==nil||[userModel.userUid isEqualToString:@""]) {
                //登录页面
                SINALoginViewController *rootViewControll = [[SINALoginViewController alloc]init ];
                SINANavLoginViewController *homeController = [[SINANavLoginViewController alloc] initWithRootViewController:rootViewControll];
                [self restoreRootViewController:homeController];
                
            } else {
                if (userModel.identitys==nil||[userModel.identitys isEqualToString:@"-1"]) {
                    SINAIdentitySelectViewController *selectControll = [[SINAIdentitySelectViewController alloc]initWithNibName:@"SINAIdentitySelectViewController" bundle:nil];
                    [self.navigationController pushViewController:selectControll animated:YES];
                }else{
                    ////用户身份标识  1学生  2教师 -1没有选择身份
                    //home页面
                    if ([userModel.identitys isEqualToString:@"1"]) {
                        SINAStudentTabBarViewController *tabBarViewController = [[SINAStudentTabBarViewController alloc]init];
                        [self restoreRootViewController:tabBarViewController];
                    } else {
                        SINATeacherTabBarViewController *tabBarViewController = [[SINATeacherTabBarViewController alloc]init];
                        [self restoreRootViewController:tabBarViewController];
                    }
                }
            }
        }else if ([code isEqualToString:@"1003"]) {
            WISAlertView *alertView =   [[WISAlertView alloc]initWithTitle:@"提示" message:@"手机号或者密码错误" sureBtn:@"确定" cancleBtn:nil];
            [alertView showXLAlertView];
        }else{
            NSString *message =responseData[@"message"];
            WISAlertView *alertView =   [[WISAlertView alloc]initWithTitle:@"提示" message:message sureBtn:@"确定" cancleBtn:nil];
            [alertView showXLAlertView];
        }
    } failure:^(NSError *error, NSInteger errCode) {
        
        [weakSelf stopLoading];
        
        WISAlertView *alertView =   [[WISAlertView alloc]initWithTitle:@"提示" message:@"登录验证失败" sureBtn:@"确定"
                                                             cancleBtn:nil];
        [alertView showXLAlertView];
    }];
}

- (UIStatusBarStyle)preferredStatusBarStyle {
    //    return UIStatusBarStyleLightContent;
    return UIStatusBarStyleLightContent;
}
-(void)viewWillAppear:(BOOL)animated{
    //    self.navigationController.navigationBarHidden = YES;
    
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:animated];
    // 这样设置状态栏样式是黑色的
    [self.navigationController.navigationBar setBarStyle:UIBarStyleBlack];
    
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSString *userPhone= [userDefaults valueForKey:@"userPhone"];
    if (userPhone==nil||[userPhone isEqualToString:@"(null)"]) {
        userPhone=@"";
    }
    self.userNameTextField.text =userPhone;
    
    [super initNavBarColor:[UIColor clearColor]];
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    // 视图消失时status bar为白色
    [self.navigationController setNavigationBarHidden:NO animated:animated];
}

-(void) backAction{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (void)restoreRootViewController:(UIViewController *)rootViewController
{
    typedef void (^Animation)(void);
    UIWindow* window = self.view.window;
    
    rootViewController.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    Animation animation = ^{
        BOOL oldState = [UIView areAnimationsEnabled];
        [UIView setAnimationsEnabled:NO];
        window.rootViewController = rootViewController;
        [UIView setAnimationsEnabled:oldState];
    };
    
    [UIView transitionWithView:window
                      duration:0.5f
                       options:UIViewAnimationOptionTransitionCrossDissolve
                    animations:animation
                    completion:nil];
}



//QQ 登录
-(void)qqLoginFunction{
    
    NSString * appid = __TencentSDKAppid_;
    [PTQQSdkCall getInstance].oauth =[[TencentOAuth alloc]initWithAppId:appid andDelegate:self];
    
    TencentOAuth * oauth = [[PTQQSdkCall getInstance]oauth];
    oauth.authMode = kAuthModeClientSideToken;
    [oauth authorize:[self getPermissions] inSafari:NO];

}

//微信登录
-(void)weixinLoginFunction{
    DLog(@"微信登录");
    
    [WXApiManager sharedManager].delegate = self;
    
    BOOL isOpenWenxin = [PTWeChatSdkCall sendAuthRequestScope: kAuthScope
                                                        State:kAuthState
                                                       OpenID:kAuthOpenID
                                             InViewController:self];
    
    NSLog(@"%d",isOpenWenxin);
}

#pragma mark WXApiManagerDelegate Method
-(void)managerDidRecvAuthResponse:(SendAuthResp *)response
{
//    NSString *strTitle = [NSString stringWithFormat:@"Auth结果"];
//    NSString *strMsg = [NSString stringWithFormat:@"code:%@,state:%@,errcode:%d", response.code, response.state, response.errCode];
//    NSLog(@"%@---%@",strMsg,strTitle);
    
    if (response.errCode == -4)
    {
        WISAlertView * alertView = [[WISAlertView alloc]initWithTitle:@"提示" message:@"拒绝授权" sureBtn:@"确定" cancleBtn:@""];
        [alertView showXLAlertView];
//         self.isClick = NO;
    }
    else if (response.errCode == -2)
    {
        WISAlertView * alertView = [[WISAlertView alloc]initWithTitle:@"提示" message:@"已取消" sureBtn:@"确定" cancleBtn:@""];
        [alertView showXLAlertView];
//         self.isClick = NO;
    }
    else
    {
        NSString * urlStr = [NSString stringWithFormat:@"https://api.weixin.qq.com/sns/oauth2/access_token?appid=%@&secret=%@&code=%@&grant_type=authorization_code",@"wx35768a01f369dc62",@"0aad08c8483fc7ddbcbfde7f937532ff",response.code];
        
        WeakSelf;
        [CXAFNHttpRequestUtils httpGetRequest:urlStr success:^(id responseData) {
            
            DLog(@"responseData === %@",responseData);
            
            [WXApiManager sharedManager].access_token = [responseData objectForKey:@"access_token"];
            [WXApiManager sharedManager].openid = [responseData objectForKey:@"openid"];
            [WXApiManager sharedManager].scope = [responseData objectForKey:@"scope"];
            [WXApiManager sharedManager].unionid = [responseData objectForKey:@"unionid"];
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1), dispatch_get_main_queue(), ^{
                
                [weakSelf getWeChatUserInfo];
                
            });
            
        } failure:^(NSError *error, NSInteger errCode) {
            
            
        }];
        
    }
}

-(void)getWeChatUserInfo
{
    NSString * infoUrlStr = [NSString stringWithFormat:@"https://api.weixin.qq.com/sns/userinfo?access_token=%@&openid=%@",[WXApiManager sharedManager].access_token,[WXApiManager sharedManager].openid];
    
    WeakSelf;
    [CXAFNHttpRequestUtils httpGetRequest:infoUrlStr success:^(id responseData) {
        
        //如果请求成功
        [WXApiManager sharedManager].nickname = [responseData objectForKey:@"nickname"];
        
        //调用绑定接口
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1), dispatch_get_main_queue(), ^{
            
            [weakSelf checkIsBindOpenId:[WXApiManager sharedManager].openid nickName:[WXApiManager sharedManager].nickname bindTag:2];
        });
        
    } failure:^(NSError *error, NSInteger errCode) {
        
        
    }];
}


#pragma mark - QQ Delegate method
- (void)tencentDidLogin
{
    if (![[PTQQSdkCall getInstance].oauth getUserInfo]) {
        
        DLog(@"获取用户信息失败");
    }
//     self.isClick = NO;
}
/**
 * 登录失败后的回调
 * \param cancelled 代表用户是否主动退出登录
 */
- (void)tencentDidNotLogin:(BOOL)cancelled
{
//     self.isClick = NO;
}

/**
 * 登录时网络有问题的回调
 */
- (void)tencentDidNotNetWork
{
//     self.isClick = NO;
}

- (void)getUserInfoResponse:(APIResponse*) response
{
    NSString * openId =[PTQQSdkCall getInstance].oauth.openId;
    NSDictionary *message = response.jsonResponse;
    
    if (openId == nil || openId.length ==0) {
        return;
    }
    
    [self checkIsBindOpenId:openId nickName:[message objectForKey:@"nickname"] bindTag:1];
}

-(void)checkIsBindOpenId:(NSString *)openid nickName:(NSString *)nickname bindTag:(NSInteger)bindTag
{
    NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
    
//    self.isClick = NO;
   
    if (bindTag ==1) {
        //qq
        [dict setObject:openid forKey:@"qqopenid"];
    }
    else if (bindTag == 2)
    {
        //微信
        [dict setObject:openid forKey:@"weixinopenid"];
    }
    
    WeakSelf;
    
    [CXAFNHttpRequestUtils httpGetRequest:[NSString stringWithFormat:@"%@%@",baseUrl,kPT_Interface_URI_ishas]  withParamters:dict success:^(id responseData) {
        
        NSString *code = responseData[@"code"];
        if ([code isEqualToString:@"1000"]) { //未绑定
            
            //缓存openid 和 nickname
            NSUserDefaults * userDefaults = [NSUserDefaults standardUserDefaults];
            
            if (bindTag ==1) {
                [userDefaults setObject:openid forKey:@"qqopenid"];
                 [userDefaults setObject:nickname forKey:@"qqnickname"];
            }
            else if (bindTag == 2)
            {
                [userDefaults setObject:openid forKey:@"weixinopenid"];
                [userDefaults setObject:nickname forKey:@"weixinnickname"];
            }
            [userDefaults synchronize];
            
            SINARegisterViewController *registerController =[[SINARegisterViewController alloc]initWithNibName:@"SINARegisterViewController" bundle:nil];
            registerController.otherLoginTag = bindTag;
            [weakSelf.navigationController pushViewController:registerController animated:YES];
        }
        else if([code isEqualToString:@"1022"]) //已绑定
        {
            [weakSelf otherLoginWith:openid nickName:nickname otherTag:bindTag];
        }
        
    } failure:^(NSError *error, NSInteger errCode) {
        
        
    }];
}

-(void)otherLoginWith:(NSString *)openId nickName:(NSString *)nickName otherTag:(NSInteger)otherTag
{
    [self.view endEditing:YES];
    
    //登录请求参数
    NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
    //1.学生phone
//    [dict setObject:userName forKey:@"phone"];
    //    NSString *passwordSign = [SINAMd5Utils md5:userPassword];
    //2.未加密密码
//    [dict setObject:userPassword forKey:@"passwords"];
    //获取系统时间戳
    NSDate* date1 = [NSDate date];
    NSTimeInterval time1 =[date1 timeIntervalSince1970];
    NSString *timeString = [NSString stringWithFormat:@"%.0f",time1];
    //3.签名时间 当前时间
    [dict setObject:timeString forKey:@"signtimes"];
    //4.唯一标识符
    NSString *uuid = [NSUUID UUID].UUIDString;
    [dict setObject:uuid forKey:@"signuid"];
    //5.签名
    NSString *signflag = [SINAMd5Utils md5:[NSString stringWithFormat:@"%@%@",uuid,timeString]];
    [dict setObject:signflag forKey:@"signflag"];
    
    if (otherTag ==1) {
    
        [dict setObject:openId forKey:@"qqopenid"];
        
        if (nickName!=nil ||nickName.length !=0) {
            [dict setObject:nickName forKey:@"qqnickname"];
        }
    }
    else if (otherTag ==2)
    {
        [dict setObject:openId forKey:@"weixinopenid"];
        
        if (nickName!=nil ||nickName.length !=0) {
         
            [dict setObject:nickName forKey:@"weixinnickname"];
        }
    }
    
    NSMutableDictionary *dict2 = [[NSMutableDictionary alloc]init];
    
    [dict2 setObject:[SINAHttpRequestUtils encodeDicParams:dict] forKey:@"sj"];
    
    [self startLoading];
    
    WeakSelf;
    [CXAFNHttpRequestUtils httpPostRequest:[NSString stringWithFormat:@"%@%@",baseUrl,userLoginUrl] withParamters:dict2 success:^(id responseData) {
        
        NSString *code = responseData[@"code"];
        
        [weakSelf stopLoading];
        
        if ([code isEqualToString:@"1000"]) {
            NSDictionary *result = responseData[@"content"];
            
            SINAUserModel *userModel=[SINAUserModel userWithDict:result];
            SINACommonUserHelper *userHelper=[SINACommonUserHelper share];
//            userModel.userPassword =userPassword;
            [userHelper saveUserModel:userModel];
            
            
            if (userModel.userUid==nil||[userModel.userUid isEqualToString:@""]) {
                //登录页面
                SINALoginViewController *rootViewControll = [[SINALoginViewController alloc]init ];
                SINANavLoginViewController *homeController = [[SINANavLoginViewController alloc] initWithRootViewController:rootViewControll];
                [self restoreRootViewController:homeController];
                
            } else {
                if (userModel.identitys==nil||[userModel.identitys isEqualToString:@"-1"]) {
                    SINAIdentitySelectViewController *selectControll = [[SINAIdentitySelectViewController alloc]initWithNibName:@"SINAIdentitySelectViewController" bundle:nil];
                    [self.navigationController pushViewController:selectControll animated:YES];
                }else{
                    ////用户身份标识  1学生  2教师 -1没有选择身份
                    //home页面
                    if ([userModel.identitys isEqualToString:@"1"]) {
                        SINAStudentTabBarViewController *tabBarViewController = [[SINAStudentTabBarViewController alloc]init];
                        [self restoreRootViewController:tabBarViewController];
                    } else {
                        SINATeacherTabBarViewController *tabBarViewController = [[SINATeacherTabBarViewController alloc]init];
                        [self restoreRootViewController:tabBarViewController];
                    }
                }
            }
        }else if ([code isEqualToString:@"1003"]) {
            WISAlertView *alertView =   [[WISAlertView alloc]initWithTitle:@"提示" message:@"手机号或者密码错误" sureBtn:@"确定" cancleBtn:nil];
            [alertView showXLAlertView];
        }else{
            NSString *message =responseData[@"message"];
            WISAlertView *alertView =   [[WISAlertView alloc]initWithTitle:@"提示" message:message sureBtn:@"确定" cancleBtn:nil];
            [alertView showXLAlertView];
        }
    } failure:^(NSError *error, NSInteger errCode) {
        
        [weakSelf stopLoading];
        
        WISAlertView *alertView =   [[WISAlertView alloc]initWithTitle:@"提示" message:@"登录验证失败" sureBtn:@"确定"
                                                             cancleBtn:nil];
        [alertView showXLAlertView];
    }];
}

- (NSMutableArray *)getPermissions
{
    NSMutableArray * g_permissions = [[NSMutableArray alloc] initWithObjects:kOPEN_PERMISSION_GET_USER_INFO,
                                      kOPEN_PERMISSION_GET_SIMPLE_USER_INFO,
                                      kOPEN_PERMISSION_ADD_ALBUM,
                                      kOPEN_PERMISSION_ADD_ONE_BLOG,
                                      kOPEN_PERMISSION_ADD_SHARE,
                                      kOPEN_PERMISSION_ADD_TOPIC,
                                      kOPEN_PERMISSION_CHECK_PAGE_FANS,
                                      kOPEN_PERMISSION_GET_INFO,
                                      kOPEN_PERMISSION_GET_OTHER_INFO,
                                      kOPEN_PERMISSION_LIST_ALBUM,
                                      kOPEN_PERMISSION_UPLOAD_PIC,
                                      kOPEN_PERMISSION_GET_VIP_INFO,
                                      kOPEN_PERMISSION_GET_VIP_RICH_INFO, nil];
    
    return g_permissions;
}

//- (void)dealloc
//{
//    [[NSNotificationCenter defaultCenter] removeObserver:self];
//}


@end
